<?php

namespace backend\controllers;

use function GuzzleHttp\Psr7\str;
use Yii;
use backend\models\Project;
use backend\models\ProjectSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use common\models\UploadForm;
use yii\web\UploadedFile;

/**
 * ProjectController implements the CRUD actions for Project model.
 */
class ProjectController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Project models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new ProjectSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Project model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Project model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Project();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Project model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Project model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Project model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Project the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Project::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    /**
     * @return string
     */
    public function actionFileUpload()
    {
        $uploadForm = new UploadForm();
        # 创建PHPExcel对象，注意，不能少了\
        $PHPExcel = new \PHPExcel();
        $excelReader = '';
        if (!Yii::$app->request->isPost) {
            return false;
        }
        $uploadForm->excelFile = UploadedFile::getInstanceByName('excelFile');
        #获取文件上传后路径
        if ($excelUrl = $uploadForm->uploadExcel()) {
            #获取文件的后缀名
            $exts = substr(strrchr($excelUrl, '.'), 1);
            #获取文件全路径
            $excelFile = Yii::$aliases['@uploadPath'] . $excelUrl;
            #根据文件的后缀名判断所需的类
            if ($exts == 'xls') {
                $excelReader = \PHPExcel_IOFactory::createReader('Excel5');
            } else if ($exts == 'xlsx') {
                $excelReader = \PHPExcel_IOFactory::createReader('Excel2007');
            }
            #判断文件是否可读
            if (!$excelReader->canRead($excelFile)) {
                return json_encode(renderJSON(400, '文件不可读!'), JSON_UNESCAPED_UNICODE);
            }
            $PHPExcel = $excelReader->load($excelFile);
            #获取所有的sheet
            $allSheet = $PHPExcel->getAllSheets();
            #数据表字段
            $fields = [
                'project_name' => '项目名称',
                'eqip_name' => '设备名称',
                'add_user_name' => '添加人员',
                'content' => '内容',
                'status' => '类型',
                'created_at' => '创建时间',
                'updated_at' => '结束时间'
            ];

            foreach ($allSheet as $sheet) {
                #获取sheet名称
                $sheet_name = trim($sheet->getTitle());
                #获取sheet的最高行和列
                $highest_column = $sheet->getHighestColumn();
                $highest_row = $sheet->getHighestRow();
                #获取所有的行列号
                $cell_collection = $sheet->getCellCollection();
                $data = [];
                foreach ($cell_collection as $cell) {
                    # 当前cell的行号
                    $row = $sheet->getCell($cell)->getRow();

                    if ($row == 1) {
                        continue;
                    }

                    # 当前cell的列
                    $column = $sheet->getCell($cell)->getColumn();

                    # A1的值(field属性)
                    $first_cell_value = $sheet->getCell($column . '1')->getFormattedValue();

                    # 当前cell的值
                    $cell_value = $sheet->getCell($cell)->getFormattedValue();
                    #返回字段
                    $field = array_search($first_cell_value, $fields);

                    if (!$field) {
                        continue;
                    }

                    if ($field == 'status') {
                        if ($cell_value == '未过期') {
                            $cell_value = 0;
                        } else {
                            $cell_value = 1;
                        }
                    }
                    if ($field == 'created_at') {
                        $cell_value = strtotime($cell_value);
                    }
                    if ($field == 'updated_at') {
                        $cell_value = strtotime($cell_value);
                    }

                    $key = $sheet_name . $highest_column . $highest_row . $row;
                    $data[$key][$field] = $cell_value;

                }
                if (!$data) {
                    return false;
                }
                $model = new Project();
                $table_name = $model->tableName();
                #数据库字段
                $field = array_keys(end($data));
                #批量插入
                $total_num = Yii::$app->db->createCommand()->batchInsert($table_name, $field, $data)->execute();

            }
            return $this->redirect('index');
        } else {
            return json_encode(renderJSON(400, '上传失败!'), JSON_UNESCAPED_UNICODE);
        }
    }

    public function actionExport()
    {

        $phpWord = new \PHPExcel();

    }
}
